package com.epam.database;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

import com.epam.util.ConfigurationManager;

public enum ConnectionPool {
	INSTANCE;

	private static final Logger LOG = Logger.getLogger(ConnectionPool.class);
	private static BlockingQueue<Connection> connections;

	public Connection takeConnection() {
		if (connections == null) {
		try {
			createConnections();
			return connections.take(); 
		} catch (InterruptedException | IOException | SQLException e) {
			LOG.error(e);
		}
		} else {
			try {
				connections.take();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				LOG.error(e);
			}
		}
		return null;
	}

	public void retreiveConnection(Connection connection) {
		try {
			connections.put(connection);

		} catch (InterruptedException e) {
			LOG.error(e);
		}
	}
	
	public synchronized void createConnections() throws IOException, SQLException {
		
		String url = ConfigurationManager.getConfig(ConfigurationManager.DATABASE_URL);
		String driverName = ConfigurationManager.getConfig(ConfigurationManager.DATABASE_DRIVER_NAME);
		String login = ConfigurationManager.getConfig(ConfigurationManager.DATABASE_LOGIN);
		String password = ConfigurationManager.getConfig(ConfigurationManager.DATABASE_PASSWORD);
		String connectionsNumber = ConfigurationManager.getConfig(ConfigurationManager.CONNECTIONS_NUMBER);
		
		Connection connection;
		try {
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			LOG.error(e);
		}		
		if (connections == null) {
			connections = new LinkedBlockingQueue<Connection>();
			for (int i = 0; i < Integer.parseInt(connectionsNumber); i++) {
				connection = DriverManager.getConnection(
						url, login, password);
				connections.add(connection);
			}

		}
	}
}